﻿using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Web;

namespace OpenAIProxy;

public class OpenAIHttpClientFactory
{
    private readonly ConcurrentDictionary<string, HttpClient> _clients = new();
    private readonly ConfigManager _configManager;
    private readonly ILogger<OpenAIHttpClientFactory> _logger;

    public OpenAIHttpClientFactory(
        ConfigManager configManager, 
        ILogger<OpenAIHttpClientFactory> logger)
    {
        _configManager = configManager;
        _logger = logger;
    }

    public HttpClient GetHttpClient(string providerName)
    {
        if (_clients.TryGetValue(providerName, out var client))
        {
            return client;
        }

        var config = _configManager.GetProviderConfig(providerName);
        if (config == null)
        {
            throw new ArgumentException($"无效的提供商名称: {providerName}");
        }

        // 创建新的HttpClient实例
        var handler = new SocketsHttpHandler
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(15),
            PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5),
            MaxConnectionsPerServer = 100
        };

        var newClient = new HttpClient(handler)
        {
            BaseAddress = new Uri(config.Endpoint),
            Timeout = TimeSpan.FromMinutes(5)
        };

        newClient.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue("Bearer", config.ApiKey);
        
        if (!string.IsNullOrEmpty(config.ApiVersion))
        {
            var queryString = HttpUtility.ParseQueryString(string.Empty);
            queryString["api-version"] = config.ApiVersion;
            newClient.BaseAddress = new Uri($"{config.Endpoint}?{queryString}");
        }

        newClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
        newClient.DefaultRequestHeaders.Add("User-Agent", "OpenAI-Proxy/1.0");
        
        _clients[providerName] = newClient;
        _logger.LogInformation($"初始化为提供商创建HttpClient: {providerName}");
        
        return newClient;
    }
}
